'''
@Project ：hdcms-scripts
@File    ：dhy_room_grouping.py
@IDE     ：PyCharm
@Author  ：朱广杰
@Date    ：2024/11/14 14:30
'''
import jsonpath
import time
from common.hd_log import mylog
from common.setting import config
from common.util.db_util import DB_Util
from common.FILE_PATH import read_excel, load_yaml_file, write_yaml
from script.api.course.api_live_room import JoinLiveApi, WishJoinRoomApi, DiscussOpenApi, DiscussCloseApi, \
    UpdateLiveInfoApi, GetRoomInfoApi, JoinLiveRoomApi, UpdateFlowHouseInfoApi, GetLiveInfoApi

# 读取测试数据
dhy_data = read_excel('/data/user_list.xlsx', '预分房100大会员')
_dhy_data = [item[0] for item in dhy_data]
common = load_yaml_file('/config/common.yml')
da_course_id = common['course_id']
da_chat_room_id = common['chat_room_id']
da_zuser_id = common['zuser_id']


# 获取直播间对应的room_id
def get_room_id(course_id: str=da_course_id):
    """
    :param course_id: 课程ID
    :return:
    """
    resp = GetLiveInfoApi(course_id).send()
    room_id = jsonpath.jsonpath(resp.json(), '$..room_id')[0]
    mylog.info(f'获取到直播间{course_id}对应的room_id是：{room_id}')
    content = load_yaml_file('/config/common.yml')
    params = {'chat_room_id': room_id}
    content.update(params)
    write_yaml('/config/common.yml', content)
    return room_id



def join_live():
    room_id = get_room_id(course_id=da_course_id)
    mylog.info(f'查询课程对应的{room_id},并更新到配置文件')
    mylog.info('开始执行用户加入直播间脚本')
    for uid in _dhy_data:
        try:
            # 查询课程对应的room_id,并更新到配置文件
            resp = JoinLiveApi(user_id=uid, chat_room_id=da_chat_room_id).send()
            resp_json = resp.json()
            code = resp_json['code']
            assert code == 200
        except Exception as e:
            mylog.error(f'用户{uid}加入直播间失败,错误信息是：{e}')
    mylog.info('用户加入直播间脚本执行成功')


# 校验用户是否进入直播间
def check_user_in_live():
    mylog.info('执行检查用户是否加入主课堂直播间')
    new_user_db = config.Config.new_user_db_config
    db_util = DB_Util(host=new_user_db['host'], user=new_user_db['user'], password=new_user_db['password'],
                      port=int(new_user_db['port']), db=new_user_db['db'])
    user_ids = tuple(_dhy_data)
    sql = (f"SELECT user_id FROM `new_user`.`im_online_user` WHERE "
           f"`chatroom_id` = '{da_chat_room_id}' AND `user_id` IN {user_ids} AND `online_status` = 'Online' LIMIT 0,1000")
    data_user_ids = db_util.select(sql=sql)
    data_user_ids = [item['user_id'] for item in data_user_ids]
    for user_id in user_ids:
        if user_id not in data_user_ids:
            mylog.info(f'用户{user_id}没有进入直播间')
    mylog.info('全部用户进入直播间')


# 编辑课程，探索流信息后，主持人开启讨论
def discuss_open():
    mylog.info('修改直播间主持人')
    try:
        UpdateLiveInfoApi(course_id=da_course_id, zuser_id=da_zuser_id).send()
        mylog.info('修改探索流配置，设置探索流模式')
        UpdateFlowHouseInfoApi(course_id=da_course_id).send()
    except Exception as e:
        mylog.error(f'修改探索流配置失败,错误信息是：{e}')
    mylog.info('主持人开启讨论')
    try:
        resp = DiscussOpenApi(da_zuser_id,da_course_id).send()
        resp_json = resp.json()
        code = resp_json['error_no']
        assert code == 0
    except Exception as e:
        mylog.error(f'主持人{da_zuser_id}开启讨论失败,错误信息是：{e}')
    time.sleep(3)
    mylog.info('主持人开启讨论成功')


#  用户同意进入预分配房间
def wish_join_room():
    mylog.info('用户同意进入预分配房间')
    for uid in _dhy_data:
        try:
            resp = WishJoinRoomApi(user_id=uid, course_id=da_course_id).send()
            resp_json = resp.json()
            code = resp_json['error_no']
            assert code == 0
        except ValueError as e:
            mylog.error(f'用户{uid}同意进入预分配房间失败,错误信息是：{e}')
    mylog.info('所有用户同意进入预分配房间')


#  检查用户是否同意开启分房
def check_user_wish_join_room():

    mylog.info('执行检查用户是否加入主课堂直播间')
    bll_course_db = config.Config.bll_course_db_config
    db_util = DB_Util(host=bll_course_db['host'], user=bll_course_db['user'], password=bll_course_db['password'],
                      port=int(bll_course_db['port']), db=bll_course_db['db'])
    user_ids = tuple(_dhy_data)
    sql = f"SELECT user_id FROM `bll_course`.`discuss_user_wish` WHERE `obj_id` = '{da_course_id}' AND `user_id` IN {user_ids} AND `discuss_wish` = '1' LIMIT 0,1000"
    data_user_ids = db_util.select(sql=sql)
    data_user_ids = [item['user_id'] for item in data_user_ids]
    for user_id in user_ids:
        if user_id not in data_user_ids:
            mylog.info(f'用户{user_id}没有同意加入房间')
    mylog.info('所有在线用户都已同意加入主课堂直播间')
    # 开启讨论后，等待30s后获取开房的数据
    mylog.info('开启讨论后，等待30s后获取开房的数据')
    time.sleep(30)



#  查询开启讨论间的discuss_id
def get_discuss_id():
    mylog.info('查询最新的discuss_id')
    bll_course_db = config.Config.bll_course_db_config
    db_util = DB_Util(host=bll_course_db['host'], user=bll_course_db['user'], password=bll_course_db['password'],
                      port=int(bll_course_db['port']), db=bll_course_db['db'])
    sql = f"select id from bll_course.discuss where obj_id = '{da_course_id}' order by discuss_open_time desc limit 1"
    mylog.info(f'执行sql：{sql}')
    data = db_util.select(sql=sql)
    discuss_id = [item['id'] for item in data][0]
    if discuss_id is None:
        mylog.info(f'{da_course_id}没有开启讨论')
        raise Exception(f'{da_course_id}没有开启讨论')
    mylog.info(f'根据{da_course_id}获取discuss_id是{discuss_id}')
    return discuss_id


#  查询预分房用户对应的discuss_room_id
def get_discuss_room_ids(discuss_id: str=None):
    mylog.info('开始查询预分房用户对应的discuss_room_id')
    if discuss_id is None:
        discuss_id = get_discuss_id()
    bll_course_db = config.Config.bll_course_db_config
    db_util = DB_Util(host=bll_course_db['host'], user=bll_course_db['user'], password=bll_course_db['password'],
                      port=int(bll_course_db['port']), db=bll_course_db['db'])
    sql = f"SELECT discuss_room_id, bind_uid FROM `bll_course`.`discuss_room_user` WHERE `discuss_id` = '{discuss_id}' "
    mylog.info(f'执行sql：{sql}, 获取到预分配房间的discuss_room_id和user_id')
    data = db_util.select(sql=sql)
    if data is None:
        mylog.info(f'{sql}没有查到数据')
        raise Exception(f'{sql}没有查到数据')
    data_user_ids = [item['bind_uid'] for item in data]
    for user_id in _dhy_data:
        if user_id not in data_user_ids:
            mylog.info(f'用户{user_id}预分房失败')
    mylog.info('查询预分房用户对应的discuss_room_id结束')
    return data

# 同意后进入预分配讨论间
def user_join_discuss_room():
    time.sleep(3)
    discuss_id = get_discuss_id()
    mylog.info(f'获取到最新的discuss_id是：{discuss_id}')
    time.sleep(3)
    discuss_room_ids = get_discuss_room_ids(discuss_id=discuss_id)
    time.sleep(5)
    for item in discuss_room_ids:
        discuss_room_id = item['discuss_room_id']
        bind_uid = item['bind_uid']
        mylog.info(f'获取到用户：{bind_uid}对应的讨论间是：{discuss_room_id}')
        try:
            resp = GetRoomInfoApi(discuss_room_id=discuss_room_id, user_id=bind_uid, discuss_id=discuss_id).send()
            resp_json = resp.json()
            code1 = resp_json['error_no']
            # 用户拉入讨论间九宫格加入trtc
            resp2 = JoinLiveRoomApi(room_id=discuss_room_id, user_id=bind_uid).send()
            resp_json2 = resp2.json()
            code2 = resp_json2['code']
            assert code1 == 0
            assert code2 == 200
        except Exception as e:
            mylog.error(f'用户{bind_uid}进入讨论间失败,错误信息是：{e}')



# 主持人关闭讨论
def discuss_close():
    mylog.info('120s后主持人关闭讨论间')
    time.sleep(120)
    try:
        resp = DiscussCloseApi(zuser_id=da_zuser_id,course_id=da_course_id).send()
        resp_json = resp.json()
        code = resp_json['error_no']
        assert code == 0
    except Exception as e:
        mylog.error(f'主持人{da_zuser_id}关闭讨论失败,错误信息是：{e}')
    time.sleep(3)
    mylog.info('主持人关闭讨论间成功')
    # 清除数据
    clear_data()


#  检查讨论间 状态
def check_discuss_status(discuss_id: str=None):
    mylog.info('执行检查讨论间状态')
    if discuss_id is None:
        discuss_id = get_discuss_id()
    bll_course_db = config.Config.bll_course_db_config
    db_util = DB_Util(host=bll_course_db['host'], user=bll_course_db['user'], password=bll_course_db['password'],
                      port=int(bll_course_db['port']), db=bll_course_db['db'])
    sql = f"SELECT current_discuss_status FROM `bll_course`.`discuss` WHERE `id` = '{discuss_id}'"
    discuss_status = db_util.select(sql=sql)
    if discuss_status[0]['current_discuss_status'] == 5:
        mylog.info('关闭讨论间成功，脚本执行成功')
        return True



# 清除数据
def clear_data():
    mylog.info('开始清除数据')
    new_user_db = config.Config.new_user_db_config
    db_util1 = DB_Util(host=new_user_db['host'], user=new_user_db['user'], password=new_user_db['password'],
                      port=int(new_user_db['port']), db=new_user_db['db'])
    bll_course_db = config.Config.bll_course_db_config
    db_util2 = DB_Util(host=bll_course_db['host'], user=bll_course_db['user'], password=bll_course_db['password'],
                      port=int(bll_course_db['port']), db=bll_course_db['db'])

    sql1 = (f"UPDATE `new_user`.`im_online_user` SET `online_status` = 'Offline' WHERE `chatroom_id` = '{da_chat_room_id}'")
    sql2 = (f"UPDATE `bll_course`.`discuss_user_wish` SET `discuss_wish` = 0 WHERE `obj_id` = '{da_course_id}'")
    db_util1.update(sql=sql1)
    db_util2.update(sql=sql2)
    mylog.info('清除数据成功')

if __name__ == '__main__':
    # get_room_id()
    join_live()
    check_user_in_live()
    discuss_open()
    wish_join_room()
    check_user_wish_join_room()
    user_join_discuss_room()
    discuss_close()
    check_discuss_status()

